import React from "react";
import styles from "@styles/login.module.scss";
import { EyeFill, EyeInvisibleFill } from "antd-mobile-icons";
import classNames from "classnames";
import useToggle from "@hooks/useToggle";
import { useEffect } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { Toast } from "antd-mobile";
import { useLoginByPasswordMutation } from "@store/apiSlice/authApiSlice";
import { useTypedDispatch } from "@store/index";
import { useNavigate } from "react-router-dom";
import { saveAuth } from "@store/slices/authSlice";
// 表单状态类型
interface FormState {
  password: string;
  mobile: string;
  isAgree: boolean;
}
// 模式验证器
const schema = z.object({
  mobile: z
    .string({
      invalid_type_error: "手机号参数类型错误",
      required_error: "请检查手机号字段名称是否正确",
    })
    .min(1, "请输入手机号")
    .regex(/^1[3-9]\d{9}$/, "手机号格式错误"),
  password: z
    .string({
      invalid_type_error: "密码参数类型错误",
      required_error: "请检查密码字段名称是否正确",
    })
    .regex(/^\w{6,24}$/, "密码需要6~24个字符"),
  isAgree: z.literal(true, {
    errorMap: () => ({ message: "请勾选协议" }),
  }),
});

export default function Password() {
  // 控制密码是否显示
  const [visible, setVisible] = useToggle(false);
  const {
    register,
    handleSubmit,
    formState: { errors, isValid },
  } = useForm<FormState>({
    // 在用户输入的过程中实时触发验证
    mode: "onChange",
    // 状态默认值
    defaultValues: { password: "", mobile: "", isAgree: false },
    // 设置表单验证器
    resolver: zodResolver(schema),
  });
  useEffect(() => {
    if (typeof errors.isAgree !== "undefined") {
      Toast.show({ content: "请勾选我已同意" });
    }
  }, [errors.isAgree]);
  var onSubmit: SubmitHandler<FormState> = (formState) => {
    console.log(formState);
  };
    // 用于实现用户登录的方法
    const [loginByPassword] = useLoginByPasswordMutation();
    // 获取 dispatch 方法
  const dispatch = useTypedDispatch();
    // 获取路由对象
    const navigate = useNavigate();
    // 表单提交
  var onSubmit: SubmitHandler<FormState> = ({ mobile, password }) => {
    // 用户登录
    loginByPassword({ mobile, password })
      .unwrap()
      .then((response) => {
        // 请求失败
        if (typeof response.success !== "undefined" && response.success === false) {
          // 消息提示
          return Toast.show(response.message);
        }
        // 请求成功, 保存用户登录凭据
        dispatch(saveAuth(response.data));
        Toast.show({
          content: "登录成功",
          afterClose: () => {
            // 跳转到个人中心页面
            navigate("/personal");
          },
        });
      });
  };
  // 渲染视图
  return (
    
    <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
    <input {...register("mobile")} />
    {errors.mobile && <p className={styles.msg}>{errors.mobile.message}</p>}
     <input {...register("password")} />
    {errors.password && <p className={styles.msg}>{errors.password.message}</p>}
    <input type="checkbox" {...register("isAgree")} />
    <button className={classNames(styles.submit, { [styles.disabled]: !isValid })}>登录</button>
  </form>
  );
}